package com.tamecode.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Author: Liqc
 * @Date: 2022/6/4 23:06
 */
public class PrivateCarReflect {

    public static void main(String[] args) throws Exception {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Class<?> aClass = classLoader.loadClass("com.tamecode.reflect.PrivateCar");
        PrivateCar privateCar = (PrivateCar) aClass.newInstance();
        Field color = aClass.getDeclaredField("color");

        // ①取消Java访问限制，访问private变量
        color.setAccessible(true);
        color.set(privateCar, "red");

        Method drive = aClass.getDeclaredMethod("drive", (Class<?>[]) null);
        // Method drive = aClass.getDeclaredMethods("drive"); // JDK 5.0 下使用

        // ②取消Java访问限制，访问protected方法
        drive.setAccessible(true);
        drive.invoke(privateCar, (Object[]) null);
    }
}
